package pkg

import (
	"fmt"
	"github.com/smartwalle/alipay/v3"
	"me/123/common/global"
)

type Payment interface {
	Pay(Subject, OutTradeNo, TotalAmount string) string
}

type Alipay struct {
	AppId     string
	PublicKey string
	NotifyUrl string
	ReturnUrl string
}

func NewAlipay() Alipay {
	return Alipay{
		AppId:     global.AppConfig.Nacos.Alipay.AppId,
		PublicKey: global.AppConfig.Nacos.Alipay.PrivateKey,
		NotifyUrl: "https://6aa44cc.r17.cpolar.top/callback",
		ReturnUrl: "https://gitee.com/",
	}
}

func (a *Alipay) Pay(Subject, OutTradeNo, TotalAmount string) string {
	var privateKey = a.PublicKey // 必须，上一步中使用 RSA签名验签工具 生成的私钥
	var client, err = alipay.New(a.AppId, privateKey, false)
	if err != nil {
		fmt.Println(err)
		return ""
	}

	var p = alipay.TradeWapPay{}
	p.NotifyURL = a.NotifyUrl
	p.ReturnURL = a.ReturnUrl
	p.Subject = Subject
	p.OutTradeNo = OutTradeNo
	p.TotalAmount = TotalAmount
	p.ProductCode = "QUICK_WAP_WAY"

	url, err := client.TradeWapPay(p)
	if err != nil {
		fmt.Println(err)
		return ""
	}

	// 这个 payURL 即是用于打开支付宝支付页面的 URL，可将输出的内容复制，到浏览器中访问该 URL 即可打开支付页面。
	var payURL = url.String()
	return payURL
}
